package com.example.hls_homework5;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    public static final String PREFERENCE_NAME = "Data";
    public static final String LAST_ACCOUNT = "last_account";
    public static final String LAST_PASSWORD = "last_password";

    Button btnLogin;
    EditText account, password;
    SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnLogin = findViewById(R.id.login_btn);
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account_text = account.getText().toString().trim();
                String password_text = password.getText().toString().trim();

                if (account_text.isEmpty() || password_text.isEmpty()) {
                    Toast.makeText(view.getContext(), "账号或密码不能空", Toast.LENGTH_SHORT).show();
                    return;
                }

                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(LAST_ACCOUNT, account_text);
                editor.putString(LAST_PASSWORD, password_text);
                editor.apply();

                Toast.makeText(view.getContext(), "账号密码已保存", Toast.LENGTH_SHORT).show();
            }
        });

        sharedPreferences = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);

        String savedAccount = sharedPreferences.getString(LAST_ACCOUNT, "");
        String savedPassword = sharedPreferences.getString(LAST_PASSWORD, "");

        if (!savedAccount.isEmpty() && !savedPassword.isEmpty()) {
            account.setText(savedAccount);
            password.setText(savedPassword);
        }
    }
}